package middleware

import (
	"net/http"
	"strings"

	"github.com/cynhard/ticket-system/internal/auth"
	"github.com/cynhard/ticket-system/internal/models"
	"github.com/gin-gonic/gin"
)

// JWTAuth JWT认证中间件
func JWTAuth(jwtSecret string) gin.HandlerFunc {
	return func(c *gin.Context) {
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code":    401,
				"message": "Authorization 请求头是必需的",
			})
			c.Abort()
			return
		}

		parts := strings.SplitN(authHeader, " ", 2)
		if len(parts) != 2 || parts[0] != "Bearer" {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code":    401,
				"message": "认证格式应为 Bearer {token}",
			})
			c.Abort()
			return
		}

		claims, err := auth.ParseToken(parts[1], jwtSecret)
		if err != nil {
			var message string
			if err == auth.ErrExpiredToken {
				message = "令牌已过期"
			} else {
				message = "无效的令牌"
			}
			c.JSON(http.StatusUnauthorized, gin.H{
				"code":    401,
				"message": message,
			})
			c.Abort()
			return
		}

		// 将用户信息存储到上下文中
		c.Set("userID", claims.UserID)
		c.Set("username", claims.Username)
		c.Set("role", claims.Role)
		c.Next()
	}
}

// RoleAuth 角色认证中间件
func RoleAuth(roles ...string) gin.HandlerFunc {
	return func(c *gin.Context) {
		role, exists := c.Get("role")
		if !exists {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code":    401,
				"message": "用户未认证",
			})
			c.Abort()
			return
		}

		userRole := role.(string)
		for _, r := range roles {
			if r == userRole {
				c.Next()
				return
			}
		}

		c.JSON(http.StatusForbidden, gin.H{
			"code":    403,
			"message": "您没有权限执行此操作",
		})
		c.Abort()
	}
}

// SupportAuth 客服认证中间件
func SupportAuth() gin.HandlerFunc {
	return RoleAuth(models.RoleSupport, models.RoleAdmin)
}

// AdminAuth 管理员认证中间件
func AdminAuth() gin.HandlerFunc {
	return RoleAuth(models.RoleAdmin)
} 